package com.signway.swmediaplayer.utils;

import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.util.Log;

import java.io.IOException;
import java.nio.ByteBuffer;

public class Utils {
    private static final String TAG = Utils.class.getName();

     public static MediaExtractor setNextExtractor(MediaExtractor extractor, String path, String type) throws IOException {
        if (extractor != null) {
            extractor.release();
        }
        MediaExtractor mediaExtractor = new MediaExtractor();
        mediaExtractor.setDataSource(path);
        Log.d(TAG, "setDataSource " + path);
        Log.d(TAG, "getTrackCount: " + mediaExtractor.getTrackCount());
        for (int i = 0; i < mediaExtractor.getTrackCount(); i++) {
            MediaFormat format = mediaExtractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            Log.d(TAG, "format : " + format + ", mime: " + mime);
            if (mime.startsWith(type)) {
                mediaExtractor.selectTrack(i);
                break;
            }
        }
        return mediaExtractor;
    }

    public enum FrameType {
         I_FRAME, P_FRAME, B_FRAME, UNKNOWN
    }

    public static FrameType getFrameType(ByteBuffer buffer) {
         return getFrameType(buffer, 0, buffer.limit());
    }

    public static String byteToString(byte[] a, int len) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; i < len; i++) {
            b.append(a[i]);
            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
        return b.toString();
    }

    public static FrameType getFrameType(ByteBuffer byteBuffer, int offset, int length) {
        byte buffer[] = new byte[5];

        if (length < offset + 5) {
            return FrameType.UNKNOWN;
        }

        byteBuffer.get(buffer, offset, 5);
        Log.d(TAG, "getFrameType: " + byteToString(buffer, 5));

        int nalType = (int)(buffer[4]) & 0x1F;

        Log.d(TAG, "getFrameType: " + nalType + ", " + byteBuffer.get(offset + 4));

        if (nalType <= 0 || nalType > 8) {
            return FrameType.UNKNOWN;
        }

        if (nalType == 5) {
            return FrameType.I_FRAME;
        } else if (nalType == 7 || nalType == 8) {
            return FrameType.P_FRAME;
        } else {
            return FrameType.B_FRAME;
        }
    }
}
